<?php
//花呗支付
// 授权回调地址，将用户的UID与授权返回码存入
//支付宝文档：https://docs.open.alipay.com/194/103296/
/*1、连接数据库 
        端口号或者地址 
        登录数据库的登录名
        登录密码
        要操作的数据库名
        */


if ($_POST) {
    $val = '---------------------POST异步通知----------------<br>';
    $val .= json_encode($_POST);
    $val .= $update;
    $val .= '-------------------------------------------------<br>';
} else {
    $val = '------------------------GET通知-------------------<br>';
    $val .= json_encode($_GET);
    $val .= '-------------------------------------------------<br>';
}

file_put_contents("hb.txt", $val, FILE_APPEND);


$link = mysqli_connect('127.0.0.1', 'ali', 'ali', 'ali', '3306');
if (!$link) {

}
//2、选择要操作的数据库
mysqli_select_db($link, 'ali');
//3、设置交互编码
mysqli_query($link, 'set names utf8');
$time = time();
//  花呗花呗花呗花呗花呗
// "trade_status":"WAIT_BUYER_PAY"

if ($_POST['trade_status'] == 'TRADE_SUCCESS') {//交易成功
    // 保存数据操作 1、将订单状态修改为成功；2、修改平台用户的余额；3、将口碑商户扣取费率后的余额转入企业支付宝
    $danhao = $_POST['out_trade_no'];
    $select = "select * from `jd_dingdan` where `danhao`='{$danhao}' limit 1";
    $arr = mysqli_query($link, $select);
    $one = mysqli_fetch_assoc($arr);

    if ($one['status'] == 1) {
        file_put_contents("hb.txt", date('Y-m-d H:i:s') . ' 订单状态已修改' . PHP_EOL, FILE_APPEND);
        echo success;
    } else {
        $trade_no = $_POST['trade_no'];
        $buyer = $_POST['buyer_logon_id'];
        $seller = $_POST['seller_email'];
        $money = $_POST['total_amount'];
        $seller_id = $_POST['seller_id'];
        $buyer_id = $_POST['buyer_id'];
        // gather
        $uid = $one['uid'];
        $select = "select * from `jd_gather` where `uid`={$uid} limit 1";
        // $select="select * from `jd_kbsh` where `uid`=222";
        $arr = mysqli_query($link, $select);
        $gather = mysqli_fetch_assoc($arr);

        if ($one['hk'] == 1) {
            $yh_money = $money * (100 - $gather['up_set']) / 100;
        } else {
//            $yh_money   =$money*($gather['path6']-$gather['up_set'])/100;

            //修改为： 订单收益 = 订单金额 × （回款费率 - （上级设定费率+分额度累加费率））
            $levelRate = 0;
//            if ($money >= 400 && $money < 600) {
//                $levelRate = 0.4;
//            } elseif ($money >= 600 && $money < 1000) {
//                $levelRate = 0.4;
//            } elseif ($money >= 1000) {
//                $levelRate = 0.6;
//            }

            if ($money >= 400 && $money < 600) {
                $levelRate = 0.8;
            } elseif ($money >= 600 && $money < 5000) {
                $levelRate = 1.6;
            } else {
                $levelRate = 0;
            }
            $yh_money = $money * ($gather['path6'] - ($gather['up_set'] + $levelRate)) / 100;
        }


        // 1、将订单状态修改为成功
        $update = "update `jd_dingdan` set `trade_no`='{$trade_no}',`buyer`='{$buyer}',`seller`='{$seller}',`seller_id`='{$seller_id}',`status`=1,`pay_money`={$money},`tx`=0,`yh_money`='{$yh_money}' where `danhao`='{$danhao}'";
        // UPDATE `jd_dingdan` SET `trade_no`='2017120821001004015319222317',`buyer`='173***3411',`seller`='nnxx***@162.com' WHERE `danhao`='20171208145556' ;
        $id1 = mysqli_query($link, $update);
        if ($id1 > 0) {
            // 2、修改平台用户的余额；
            file_put_contents("hb.txt", date('Y-m-d H:i:s') . ' 订单状态修改成功' . PHP_EOL, FILE_APPEND);


            if ($one['hk'] == 1) {
                $total = $gather['money'] + $money * (100 - $gather['up_set']) / 100;
            } else {
                $total = $gather['money'] + $money * ($gather['path6'] - $gather['up_set']) / 100;
            }
            $update = "update `jd_dingdan` set `t_money`='{$total}' where `danhao`='{$danhao}'";

            mysqli_query($link, $update);

            // $total=$gather['money']+$money*(1-$gather['path1']/100);
            // 修改平台用户余额

            $total_money = floatval($total) + floatval($gather['yongjin']);
            $update = "update `jd_gather` set `fenrun`={$total_money} where `uid`={$uid}";
            $id2 = mysqli_query($link, $update);

            if ($id2 > 0) {
                file_put_contents("hb.txt", date('Y-m-d H:i:s') . ' 平台用户余额修改成功' . PHP_EOL, FILE_APPEND);

                if ($one['hk'] == 1) {
                    //不回款不需制定
                } else {
                    // 插播：制定对应的转账表
//                    $trans_money = $money * (1 - $gather['path6'] / 100);
                    //修改为 收款码设置的费率

                    //取出收款码回款费率
                    $shoukuanma_id = $one['shoukuanma_id'];
                    $shoukuanma_select = "select * from `jd_shoukuanma` WHERE `id`={$shoukuanma_id}";
                    $shoukuanma_arr = mysqli_query($link, $shoukuanma_select);
                    $shoukuanma = mysqli_fetch_assoc($shoukuanma_arr);

                    $trans_money = $money * (1 - $shoukuanma['hb'] / 100);
                    $trans_money = number_format($trans_money, 2, '.', '');
                    $out_biz_no = 'hb' . date("YmdHis") . rand(1000, 9999);
                    $returninfo = [
                        'order_info' => $one,
                        'shoukuanma_id' => $shoukuanma_id,
                        'shoukuanma' => $shoukuanma,
                        'transmoney' => $trans_money
                    ];
                    file_put_contents("hb.txt", date('Y-m-d H:i:s') . 'return.php回款金额信息：' . json_encode($returninfo) . PHP_EOL, FILE_APPEND);
                    $add = "insert into `jd_trans` (`trade_no`,`uid`,`money`,`buyer_id`,`out_biz_no`) values ('{$trade_no}','{$uid}','{$trans_money}','{$buyer_id}','{$out_biz_no}')";
                    $trans_result = mysqli_query($link, $add);
                    if ($trans_result) {

                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '回款表写入成功' . PHP_EOL, FILE_APPEND);
                    } else {
                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '回款表写入失败' . PHP_EOL, FILE_APPEND);
                    }


                    //为给自己增加分润
                    $selfDivide = $money * ($shoukuanma['hb'] - $gather['up_set']) / 100;
                    $selfDivide = number_format($selfDivide, 2, '.', '');
                    file_put_contents("hb.txt", date('Y-m-d H:i:s') . '给自己分润金额: ' . $selfDivide . PHP_EOL, FILE_APPEND);

                    $add = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`,`divide`,`time`) values ('{$uid}','{$danhao}','{$trade_no}','{$uid}','','{$money}',1,0,'{$selfDivide}',$time)";
                    file_put_contents("hb.txt", date('Y-m-d H:i:s') . '给自己分润金额sql: ' . $add . PHP_EOL, FILE_APPEND);

                    $selfDivideAddRes = mysqli_query($link, $add);

                    if ($selfDivideAddRes) {

                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '给自己分润成功' . PHP_EOL, FILE_APPEND);
                    } else {
                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '给自己分润失败' . PHP_EOL, FILE_APPEND);
                    }

                }


                // 3、制定分账信息  通过seller在口碑商户表中找到使用的授权令牌
                $add = "insert into jd_split (`seller_id`,`money_in`,`trade_no`) values ('{$seller_id}','{$money}','{$trade_no}')";
                $id3 = mysqli_query($link, $add);
                if ($id3 > 0) {
                    file_put_contents("hb.txt", date('Y-m-d H:i:s') . '分账信息写入成功' . PHP_EOL, FILE_APPEND);


                    // 4、查询是否有上级 有的话需要给上级的余额增加该笔订单的%
                    $select = "select * from `jd_ptyh` where `uid`={$one[uid]} limit 1";
                    $arr = mysqli_query($link, $select);
                    $ptyh = mysqli_fetch_assoc($arr);  //当前用户

                    if ($ptyh['pid'] == 0 || $ptyh['pid'] == 1 || $ptyh['level'] > 4) {//没有上级或者4级以下
                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '没有上级或者4级以下：' . PHP_EOL, FILE_APPEND);

                        echo success;
                    } else {
                        // 查找上一级
                        /** 父级 start */
                        $select = "select * from `jd_ptyh` where `uid`={$ptyh[pid]} limit 1";
                        $arr = mysqli_query($link, $select);
                        $parentPtyh = mysqli_fetch_assoc($arr);  //当前用户的上级

                        $select = "select * from `jd_gather` WHERE `uid`={$ptyh[pid]} limit 1";
                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '上级分润gather：'. $select . PHP_EOL, FILE_APPEND);

                        $arr = mysqli_query($link, $select);
                        $fatherGather = mysqli_fetch_assoc($arr);
                        $firstLevelDivide = $money * ($gather['up_set'] - $fatherGather['up_set']) / 100;
                        $firstLevelDivide = number_format($firstLevelDivide, 2, '.', '');
                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '上级分润金额：'. $firstLevelDivide . PHP_EOL, FILE_APPEND);


                        $shou = $one['uid'];
                        $parent = $parentPtyh['uid'];
                        $danhao = 'hb' . date("YmdHis") . rand(1000, 9999);

                        /** 爷爷级  start */
                        $grandfatherSql = "select * from `jd_ptyh` WHERE `uid` = {$parentPtyh[pid]} limit 1";
                        $grandfatherArr = mysqli_query($link, $grandfatherSql);
                        $grandfather = mysqli_fetch_assoc($grandfatherArr);

                        $select = "select * from `jd_gather` WHERE `uid`={$parentPtyh[pid]} limit 1";
                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '上上级gather：'. $select . PHP_EOL, FILE_APPEND);

                        $arr = mysqli_query($link, $select);
                        $grandfatherGather = mysqli_fetch_assoc($arr);
                        $secondLevelDivide = $money * ($fatherGather['up_set'] - $grandfatherGather['up_set']) / 100;
                        $secondLevelDivide = number_format($secondLevelDivide, 2, '.', '');
                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '上上级分润金额：'. $secondLevelDivide . PHP_EOL, FILE_APPEND);

                        $grandfatherUid = $parentPtyh['pid'];
                        $add = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`,`time`,`divide`,`status`) values ('{$parent}','{$danhao}','{$trade_no}','{$shou}','{$parent}','{$money}',1,1,$time,$firstLevelDivide,1),('{$grandfatherUid}','{$danhao}','{$trade_no}','{$shou}','{$grandfatherUid}','{$money}',1,2,$time,$secondLevelDivide,1)";
                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '分润sql：'. $add . PHP_EOL, FILE_APPEND);

                        $fatherDividendRes = mysqli_query($link, $add);

                        if ($fatherDividendRes) {

                            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '给上级分润成功' . PHP_EOL, FILE_APPEND);
                        } else {
                            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '给上级分润失败' . PHP_EOL, FILE_APPEND);
                        }
                        /** 父级 end */

                        /** 爷爷级  start */
//                        $grandfatherSql = "select * from `jd_ptyh` WHERE `uid` = {$parentPtyh[pid]} limit 1";
//                        $grandfatherArr = mysqli_query($link, $grandfatherSql);
//                        $grandfather = mysqli_fetch_assoc($grandfatherArr);
//
//                        $select = "select * from `jd_gather` WHERE `uid`={$parentPtyh[pid]} limit 1";
//                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '上上级gather：'. $select . PHP_EOL, FILE_APPEND);
//
//                        $arr = mysqli_query($link, $select);
//                        $grandfatherGather = mysqli_fetch_assoc($arr);
//                        $secondLevelDivide = $money * ($fatherGather['up_set'] - $grandfatherGather['up_set']) / 100;
//                        $secondLevelDivide = number_format($secondLevelDivide, 2, '.', '');
//                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '上上级分润金额：'. $secondLevelDivide . PHP_EOL, FILE_APPEND);
//
//                        $grandfatherUid = $parentPtyh['pid'];
//                        $grandfatherDividend = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`,`time`,`divide`,`status`) values ('{$grandfatherUid}','{$danhao}','{$trade_no}','{$shou}','{$grandfatherUid}','{$money}',1,2,$time,$secondLevelDivide,1)";
//                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '上上级分润sql: ' . $grandfatherDividend . PHP_EOL, FILE_APPEND);
//                        $grandfatherResult = mysqli_query($link,$grandfatherDividend);
//                        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '给上上级分润结果: ' . json_encode($grandfatherResult) . PHP_EOL, FILE_APPEND);
//
//                        if ($grandfatherResult) {
//
//                            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '给上上级分润成功' . PHP_EOL, FILE_APPEND);
//                        } else {
//                            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '给上上级分润失败' . PHP_EOL, FILE_APPEND);
//                        }


                        if ($fatherDividendRes > 0 ) {
                            echo success;
                        } else {
                            echo fail;
                        }

                    }


                } else {
                    file_put_contents("hb.txt", date('Y-m-d H:i:s') . '分账信息写入失败' . PHP_EOL, FILE_APPEND);

                    echo fail;
                }

            } else {
                file_put_contents("hb.txt", date('Y-m-d H:i:s') . '平台用户余额修改失败' . PHP_EOL, FILE_APPEND);

                echo fail;
            }
        } else {
            file_put_contents("hb.txt", date('Y-m-d H:i:s') . '订单状态修改失败' . PHP_EOL, FILE_APPEND);

            echo fail;
        }
    }


}









